package order

import (
	"github.com/go-xorm/xorm"
	"hotel_Manager_Api/model/dbModel"
	"github.com/go-martini/martini"
	"hotel_Manager_Api/util"
	"time"
	"github.com/martini-contrib/encoder"
	"hotel_Manager_Api/model/dto"
	"fmt"
)


func NewOrder(orders []dbModel.Order,db *xorm.Engine,generator util.IdGenerator) (int,error) {
	for i,_ := range orders{
		id := generator.GenerateNewId()
		orders[i].Status = dbModel.Accept
		orders[i].Id = id
		orders[i].CreateTime = time.Now()
	}
	_,err:=db.Insert(orders)
	if err!= nil{
		return 500,err
	}
	return 201,nil
}

func GetOrders(params martini.Params,db *xorm.Engine,enc encoder.Encoder) (int,[]byte,error) {
	deskOrderId,err := util.ParamaterToInt64(params,"deskOrderId")
	if err!= nil{
		return 400,nil,err
	}
	orders := make([]dto.FoodOrder,0)
	sql := getOrderSelectSql()
	sql+=` where o.deskOrderId = ? order by id desc`

	err = db.SQL(sql,deskOrderId).Find(&orders)
	if err!=nil{
		fmt.Print(err)
		return 500,nil,err
	}
	return 200,encoder.Must(enc.Encode(orders)),nil
}

func getOrderSelectSql()string{
	sql := "SELECT o.id,o.foodId,o.count,o.status,o.createTime,food.name,food.price,unit.name as unit"
	sql += " FROM `order` o "
	sql += `inner join food on o.foodId = food.id
			inner join unit on food.unitId = unit.id`
	return sql;
}